package hn.cch.advanced.concurrent.atomic;

import hn.cch.advanced.concurrent.ExecutorServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceDemo {

    private static final Logger logger = LoggerFactory.getLogger(AtomicReferenceDemo.class);


    private AtomicReference<BigDecimal> atomic;

    public void runAtomic(BigDecimal cost) {
        BigDecimal prev, next;
        do {
            prev = atomic.get();
            next = prev.subtract(cost);
        } while (!atomic.compareAndSet(prev, next)); // 循环判断设置
    }

    public static void main(String[] args) {
        int init = 100000;
        int cost = 10;
        BigDecimal initDecimal = new BigDecimal(init);
        BigDecimal costDecimal = new BigDecimal(cost);
        AtomicReferenceDemo demo = new AtomicReferenceDemo();
        demo.atomic = new AtomicReference<>(initDecimal);

        int n = 3;
        ExecutorService threadPool = Executors.newFixedThreadPool(n);
        for (int i = 0; i < init / cost; i++) {
            threadPool.execute(() -> demo.runAtomic(costDecimal));
        }

        threadPool.shutdown();
        ExecutorServiceUtil.complete(threadPool);
        logger.debug("atomic:{}", demo.atomic.get());


    }

}
